package com.adhere.security.context;

import com.adhere.common.constants.SecurityConstants;
import com.adhere.common.constants.SystemConstants;
import com.adhere.common.utils.TypeConvertUtils;
import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取当前线程变量中的 用户id、用户名称、Token等信息
 * 注意：
 *      依赖拦截器读取请求头中的 token 和 用户信息来维护的
 *
 * https://blog.csdn.net/a3212/article/details/82142801
 *
 * @author WT
 */
public class SecurityContextHolder {

    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? SystemConstants.EMPTY_STR : value);
    }

    public static String get(String key) {
        Map<String, Object> map = getLocalMap();
        return TypeConvertUtils.objectToString(map.getOrDefault(key, SystemConstants.EMPTY_STR));
    }

    @SuppressWarnings("unchecked")
    public static <T> T get(String key, Class<T> clazz) {
        Map<String, Object> map = getLocalMap();
        return (T) map.getOrDefault(key, null);
    }

    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static void setLocalMap(Map<String, Object> threadLocalMap) {
        THREAD_LOCAL.set(threadLocalMap);
    }

    public static Long getUserId() {
        return Long.parseLong(get(SecurityConstants.USER_ID));
    }

    public static void setUserId(String account) {
        set(SecurityConstants.USER_ID, account);
    }

    public static String getUserName() {
        return get(SecurityConstants.LOGIN_NAME);
    }

    public static void setUserName(String username) {
        set(SecurityConstants.LOGIN_NAME, username);
    }

    public static String getUserKey() {
        return get(SecurityConstants.USER_KEY);
    }

    public static void setUserKey(String userKey) {
        set(SecurityConstants.USER_KEY, userKey);
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }

}
